<template>
  <div>
    <!-- 测试区域 -->
    <el-card style="margin-bottom: 20px;">
      <div slot="header">菜单状态测试</div>
      <el-alert
        title="左侧菜单应该已经显示"
        type="success"
        :closable="false"
        show-icon>
      </el-alert>
      <p>如果您能看到这个页面，说明路由和布局组件工作正常。</p>
      <p>左侧菜单应该包含：仪表盘、成员管理、家族树、审核管理、系统管理等选项。</p>
    </el-card>

    <el-row :gutter="20">
      <el-col :span="12">
        <el-card>
          <div slot="header">家族人口统计</div>
          <div ref="populationChart" style="height:300px;"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card>
          <div slot="header">分支人数统计</div>
          <div ref="branchPopulationChart" style="height:300px;"></div>
        </el-card>
      </el-col>
    </el-row>
    <el-row style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <div slot="header">迁徙路线可视化</div>
          <div ref="migrationMap" id="migrationMap" style="height:400px;width:100%;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import request from '@/api/request';
import * as amap from '@/utils/amap-simple';
export default {
  mounted() {
    this.initPopulation();
    this.initMigrationMap();
  },
  methods: {
    async initPopulation() {
      const data = await request({ url: '/api/v1/statistics/population', method: 'get', params: { clanId: 1 } });

      // 1. 分支-世代人数对比
      const popGen = data.populationByBranchGeneration || {};
      const allGenerations = Array.from(new Set([].concat(...Object.values(popGen).map(obj => Object.keys(obj))))).sort((a, b) => a - b);
      const branchNames = Object.keys(popGen);
      const series = branchNames.map(branch => ({
        name: branch,
        type: 'bar',
        data: allGenerations.map(gen => popGen[branch][gen] || 0)
      }));
      const popGenChart = echarts.init(this.$refs.populationChart);
      popGenChart.setOption({
        title: { text: '分支-世代人数对比' },
        tooltip: { trigger: 'axis' },
        legend: { data: branchNames },
        xAxis: { type: 'category', data: allGenerations, name: '世代' },
        yAxis: { type: 'value', name: '人数' },
        series
      });

      // 2. 分支人数统计
      if (data.branchPopulationMap) {
        const branchChart = echarts.init(this.$refs.branchPopulationChart);
        branchChart.setOption({
          title: { text: '分支人数统计' },
          tooltip: {},
          xAxis: { type: 'category', data: Object.keys(data.branchPopulationMap) },
          yAxis: { type: 'value' },
          series: [{ type: 'bar', data: Object.values(data.branchPopulationMap) }]
        });
      }
    },
    async initMigrationMap() {
      const res = await request({ url: '/api/v1/statistics/migration', method: 'get', params: { clanId: 1 } });
      const migrationList = res.migrationList || [];
      // 初始化地图，传id字符串
      const map = await amap.initMap('migrationMap', {
        zoom: 5,
        center: [112.938814, 28.228209],
      });
      for (const [idx, item] of migrationList.entries()) {
        // 解析迁徙路线
        if (item.migrationRoute) {
          try {
            // 1. 先解析为对象数组
            const coordObjs = JSON.parse(item.migrationRoute); // [{lng, lat}, ...]
            // 2. 转为二维数组
            const coords = Array.isArray(coordObjs)
              ? coordObjs.map(p => [p.lng, p.lat])
              : [];
            if (coords.length > 1) {
              // 颜色色板
              const colorPalette = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#8A2BE2', '#00BFFF', '#FF69B4'];
              const routeColor = colorPalette[idx % colorPalette.length];
              // 主线：分支专属色+阴影+圆角+虚线+箭头
              const polyline = new window.AMap.Polyline({
                path: coords,
                strokeColor: routeColor,
                strokeWeight: 5,
                strokeOpacity: 0.85,
                isOutline: true,
                outlineColor: '#fff',
                lineJoin: 'round',
                lineCap: 'round',
                showDir: true,
                strokeStyle: 'dashed',
                icons: [{
                  icon: new window.AMap.Icon({
                    image: 'https://img.icons8.com/ios-filled/50/409EFF/right.png',
                    size: new window.AMap.Size(32, 32),
                    imageSize: new window.AMap.Size(32, 32)
                  }),
                  offset: 'center',
                  repeat: '80px'
                }]
              });
              polyline.setMap(map);

              // 动态流动小圆点动画（同色系）
              const flowMarker = new window.AMap.Marker({
                map,
                position: coords[0],
                icon: new window.AMap.Icon({
                  image: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png',
                  size: new window.AMap.Size(16, 16),
                  imageSize: new window.AMap.Size(16, 16)
                }),
                offset: new window.AMap.Pixel(-8, -8),
                zIndex: 120
              });
              let flowIdx = 0;
              let flowTimer = setInterval(() => {
                flowIdx++;
                if (flowIdx >= coords.length) flowIdx = 0;
                flowMarker.setPosition(coords[flowIdx]);
              }, 200);

              // 起点/终点标记
              const startMarker = await amap.createMarker(map, coords[0], { label: { content: item.branchName + ' 起点' } });
              startMarker.setMap(map);
              const endMarker = await amap.createMarker(map, coords[coords.length-1], { label: { content: item.branchName + ' 终点' } });
              endMarker.setMap(map);
            }
          } catch (e) { console.error(e); }
        }
        // 额外地图标记
        if (item.mapMarker) {
          try {
            const markerObj = JSON.parse(item.mapMarker); // {lng, lat}
            const markerCoord = [markerObj.lng, markerObj.lat];
            const marker = await amap.createMarker(map, markerCoord, { label: { content: item.branchName } });
            marker.setMap(map);
          } catch (e) { console.error(e); }
        }
      }
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style> 